﻿using DLL.Standard.Infrastructure.Encryption;
using System.Globalization;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;

namespace DLL.NET.BindingInjector
{
    public class CJiaMi
    {
        #region ========MD5加密========

        //md5 加密
        public static string MD5Encrypt(string strText)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strText));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        public static string GetMd5Hash(Stream input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(input);
            input.Seek(0, SeekOrigin.Begin);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

        // Verify a hash against a string. md5值不区分大小写
        public static bool VerifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = MD5Encrypt(input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion ========MD5加密========

        #region ========SHA1加密========

        public string SHA1Encryption(string userPassword)
        {
            string SHA1EncrypPassword = "";// System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(userPassword, "SHA1");

            return SHA1EncrypPassword;
        }

        #endregion ========SHA1加密========

        #region ========DES加密========

        public static string DESEncryption(string userPassword, byte[] Key, byte[] Iv)
        {
            Byte[] password = Encoding.ASCII.GetBytes(userPassword);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream();
            ICryptoTransform iCryrt = des.CreateEncryptor(Key, Iv);
            CryptoStream cs = new CryptoStream(ms, iCryrt, CryptoStreamMode.Write);
            cs.Write(password, 0, userPassword.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }

        #endregion ========DES加密========

        #region ========TripleDES加密========

        public static string TripleEncryption(string userPassword, string Key)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(userPassword);
            byte[] keys = ASCIIEncoding.ASCII.GetBytes(Key);
            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            tripleDES.Key = keys;  //长度必须为16位或则是24位
            tripleDES.Mode = CipherMode.ECB; //设置运算模式
            ICryptoTransform transform = tripleDES.CreateEncryptor();
            return Convert.ToBase64String(transform.TransformFinalBlock(bytes, 0, bytes.Length));
        }

        #endregion ========TripleDES加密========

        #region jiami

        ///解密
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.Default.GetString(ms.ToArray());
        } /// <summary>

          /// 加密
          /// </summary>
          /// <param name="pToEncrypt"></param>
          /// <param name="sKey"></param>
          /// <returns></returns>
        public static string Encrypt(string pToEncrypt, string sKey)
        {
            System.Security.Cryptography.DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        #endregion jiami
    }

    public class CYanZheng
    {
        public static string SHA256EncryptString(string data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] hash = SHA256.Create().ComputeHash(bytes);

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                builder.Append(hash[i].ToString("X2"));
            }
            return builder.ToString();
        }

        public static string GetShouquanma(string s)
        {
            if (s.Length != 13)
            {
                return "000000000000000000";
            }

            string a = s.Substring(0, 7);
            string b = s.Substring(7);

            string ha = "0" + SHA256EncryptString(a);
            //b68526bb7bafd866d350bdae3ce78564ad7a1eb83cda4e09c3a298bf967aeade
            string hb = "0" + SHA256EncryptString(b);

            BigInteger bigIntegera = BigInteger.Parse(ha, NumberStyles.HexNumber);
            BigInteger bigIntegerb = BigInteger.Parse(hb, NumberStyles.HexNumber);

            int lengtha = ha.Length;
            int lenght = hb.Length;
            BigInteger bigIntegers = BigInteger.Subtract(bigIntegera, bigIntegerb);
            BigInteger babs = BigInteger.Abs(bigIntegers);

            string subs = babs.ToString().Substring(0, 5);
            return s + subs;
        }

        public static bool YanzhengShouquanma(string s)
        {
            try
            {
                string ab = s.Substring(0, 13);
                string y = s.Substring(13);
                string yanzheng = GetShouquanma(ab).Substring(13);
                return yanzheng == y;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }

    public class CInjectorCount
    {
        public string AllowCount { get; set; }
        public string CurrentUesdCount { get; set; }
    }

    public class WR_CInjectorCount
    {
        private string fileName = @"Param\";

        private static CInjectorCount Read()
        {
            XmlSerializer xmlFormat = new XmlSerializer(typeof(CInjectorCount));
            try
            {
                //string str2 = Application.StartupPath;
                string str_1 = AppDomain.CurrentDomain.BaseDirectory;
                string filePath = "C:\\Windows\\System32\\bing.xml";
                if (File.Exists(filePath))
                {
                    Stream fstream = File.OpenRead(filePath);
                    CInjectorCount obj = (CInjectorCount)xmlFormat.Deserialize(fstream);
                    fstream.Close();
                    fstream.Dispose();
                    return obj;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static bool Read(ref int AllowCount, ref int CurrentUesdCount)
        {
            CInjectorCount injecotr = Read();
            if (injecotr == null)
                return false;
            string[] ja = RJ_DES.DecryptDES(injecotr.AllowCount).Split("_");
            string[] jc = RJ_DES.DecryptDES(injecotr.CurrentUesdCount).Split("_");
            if ((ja.Length == 2 && jc.Length == 2))
            {
                AllowCount = Convert.ToInt32(ja[1]);
                CurrentUesdCount = Convert.ToInt32(jc[1]);
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool Save(int AllowCount, int currentUsedCount)
        {
            CInjectorCount injecotr = new CInjectorCount();
            string ja = RJ_DES.EncryptDES("AC_" + AllowCount.ToString());
            string jc = RJ_DES.EncryptDES("AC_" + currentUsedCount.ToString());
            injecotr.AllowCount = ja;
            injecotr.CurrentUesdCount = jc;
            return Save(injecotr);
        }

        private static bool Save(CInjectorCount obj)
        {
            XmlSerializer xmlFormat = new XmlSerializer(typeof(CInjectorCount));
            try
            {
                //现在将数据保存到本地的一个文件中
                string str_1 = AppDomain.CurrentDomain.BaseDirectory;
                string filePath = "C:\\Windows\\System32\\bing.xml";
                Stream fstream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                xmlFormat.Serialize(fstream, obj);
                fstream.Close();
                fstream.Dispose();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
    }
}